<template>
  <div class="all">
    <el-card class="box-card">
      <template #header>
        <span>{{tClass.className}}:</span><span v-if="viewHomeworkState==0">要交的作业</span><span v-else>已结束作业</span>
      </template>
      <div v-if="viewHomeworkState==0" >
        <el-table v-if="viewHomeworkState==0" :data="tclassHomeworkDetail.data" stripe style="width: 100%">
        <el-table-column prop="id" label="序号" width="100" />
        <el-table-column prop="title" label="作业题目" width="260">
          <template #default="scope">
            <el-tooltip content="点击查看题目详情" placement="top">
              <span class="col2-cell-style" @click="viewQuestion(scope.row)">{{
                scope.row.title
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="总分" width="120" />
        <el-table-column prop="language" label="语言" width="200" />
        <el-table-column prop="beginTime" label="发布时间" width="200" />
        <el-table-column prop="endTime" label="结束时间" width="200" />
        <el-table-column
                        prop="submitStatus"
                        label="状态"
                        align="center">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.submitStatus == 2" disable-transitions>已提交</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.submitStatus == null" disable-transitions>未提交</el-tag>
                    </template>
                </el-table-column>
      </el-table>
      
      </div>
      <div v-else>
        <el-table  :data="tclassHomeworkDetail.data" stripe style="width: 100%">
        <el-table-column prop="id" label="序号" width="100" />
        <el-table-column prop="title" label="作业题目" width="260">
          <template #default="scope">
            <el-tooltip content="点击查看题目详情" placement="top">
              <span class="col2-cell-style" @click="viewQuestion(scope.row)">{{
                scope.row.title
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="总分" width="120" />
        <el-table-column prop="language" label="语言" width="200" />
        <el-table-column prop="beginTime" label="发布时间" width="200" />
        <el-table-column prop="endTime" label="结束时间" width="200" />
        <el-table-column
                        prop="submitStatus"
                        label="状态"
                        align="center">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.submitStatus == 2" disable-transitions>已提交</el-tag>
                        <el-tag type="danger" v-else disable-transitions>未提交</el-tag>
                    </template>
                </el-table-column>
      </el-table>

      <!-- <Pagination :currentPage="noHomeworkCurrPage" :pageSize="noHomeworkPageSize" :total="noHomeworkTotal"
                    :handleSizeChange="handleSizeChange1" :handleCurrentChange="handleCurrentChange1"></Pagination> -->
      </div>
      <Pagination :currentPage="HomeworkCurrPage" :pageSize="HomeworkPageSize" :total="HomeworkTotal"
                    :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>
      

    </el-card>

    <el-card class="box-card1">
      <template #header>
        <div class="card-header1">
          <span>作业操作</span>
        </div>
      </template>
    <div class="submitted" @click="debounce(viewHomework(2),3000,true)">查看要交的作业</div>
    <div class="over" @click="debounce(viewHomework(1),3000,true)">查看已结束作业</div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive,ref,onMounted } from "vue";
import API from '../api/trainer'
import Pagination from '@/components/Pagination.vue'
import { ElMessage,ElMessageBox, ElStep  } from 'element-plus'
import { useRouter } from "vue-router";
const router = useRouter();

    onMounted(()=>{
        tClass.className=JSON.parse(localStorage.getItem("tClass")).name;
        currentClassId.value = JSON.parse(localStorage.getItem("tClass")).id
        debounce(viewHomeworkByClass(2),3000,true)
    })

    let viewHomeworkState = ref(0)
    let tClass= reactive({
      className:''
    })
    function getThisDate(originalDateTime){
    
    const date = new Date(originalDateTime);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    let formattedDateTime = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;

      return formattedDateTime
    }
    const currentClassId = ref(0)
    const HomeworkCurrPage = ref(1)
    const HomeworkPageSize = ref(20)
    const HomeworkTotal = ref(0)
    function handleSizeChange (val){
      HomeworkPageSize.value = val
      if(viewHomeworkState.value==0)
      viewHomeworkByClass(2)
      else
      viewHomeworkByClass(1)
    }
    function handleCurrentChange (val){
      HomeworkCurrPage.value = val
      if(viewHomeworkState.value==0)
      viewHomeworkByClass(2)
      else
      viewHomeworkByClass(1)
    }
    //防抖
    function debounce(fn, delay, immediate = false) {
      // timer的作用域在外层函数作用域
      let timer = null;
      return (n) => {
        immediate && !timer && fn.call(this, n);
        timer && clearInterval(timer);
        timer = setTimeout(() => {
          !immediate && fn.call(this, n);
          clearTimeout(timer);
          timer = null;
        }, delay);
      };
    }

    async function viewHomeworkByClass(type) {
                tclassHomeworkDetail.data = []
                let getHomeworkParams = {
                    pageNumber : HomeworkCurrPage.value,
                    pageSize : HomeworkPageSize.value,
                    trainClassId : currentClassId.value,
                    type : type
                }
                let token = localStorage.getItem('token')
                API.getHomework( getHomeworkParams,token).then(res=>{
                        if(res.data.success==true){
                                console.log(res.data)
                                //另一个API
                                let isWoring  = true
                                //这两个数据用于遍历两个数组
                                if(!res.data.content){
                                  
                                    HomeworkTotal.value = 0
                                  
                                }
                                else{
                                  HomeworkTotal.value = res.data.content.total
                                }
                                    
                                   
                                if(res.data.content && res.data.content.records[0]){
                                    for(let i = 0;i<res.data.content.records.length;i++)
                                                {   
                                                    
                                                    tclassHomeworkDetail.data[i] = res.data.content.records[i]
                                                    
                                                    tclassHomeworkDetail.data[i].beginTime = getThisDate(tclassHomeworkDetail.data[i].beginTime)
                                                    tclassHomeworkDetail.data[i].endTime = getThisDate(tclassHomeworkDetail.data[i].endTime)

                                                    let languageArr = tclassHomeworkDetail.data[i].language.split(',')
                                                  // language编号对应成语言
                                                  const languageMap = {
                                                    '1': 'C',
                                                    '2': 'C++',
                                                    '3': 'JAVA',
                                                    '4': 'PASCAL',
                                                    '5': 'PYTHON3',
                                                    '6': 'RUBY'
                                                  };
                                                  for (let j = 0; j < languageArr.length; j++) {
                                                    const languageCode = languageArr[j];
                                                    if (languageMap[languageCode]) {
                                                      languageArr[j] = languageMap[languageCode];
                                                    }
                                                  }
                                                  tclassHomeworkDetail.data[i].language=languageArr.join(',')
                                          
                                                }
                                                if(isWoring){
                                                    
                                                    ElMessage.success('请求作业成功')
                                                }
                                                else{
                                                    ElMessage.error('请求作业失败')
                                                }
                                }
                                else{
                                    tclassHomeworkDetail.data = []
                                    ElMessage.success("请求作业成功")
                                }
                        
                        }else {
                        console.log(res.data)
                        ElMessage.error("获取作业失败，请联系管理员")
                        }
                }).catch(e=>{
                  console.log(e)
                })
            }
// 弹窗关闭触发
  function closeHomeworkDialog(){
    tclassHomeworkDetail.data = []
  }
  //分类作业结束
  const tclassHomeworkDetailNotS = reactive({data:[]})//已经结束
  const tclassHomeworkDetailISS = reactive({data:[]})//未结束
    let tclassHomeworkDetail = reactive({data:[
      {
        number: 1,
        question: "斐波那契数列中的合数",
        score: 100,
        buildTime: "2023-11-28 19:00:00",
        endTime: "2023-11-28 20:00:00",
      },
      {
        number: 2,
        question: "个人所得税【C/C++/Java/Python】",
        score: 50,
        buildTime: "2023-11-28 19:00:00",
        endTime: "2023-11-28 20:00:00",
      },
      {
        number: 3,
        question: "判断闰年【C/C++/Java/Python】",
        score: 80,
        buildTime: "2023-11-28 19:00:00",
        endTime: "2023-11-28 20:00:00",
      },
      {
        number: 4,
        question: "打印ASCII码【C/C++/Java/Python】",
        score: 60,
        buildTime: "2023-11-28 19:00:00",
        endTime: "2023-11-28 20:00:00",
      },
    ]});
    function viewHomework(flag) {
        viewHomeworkState.value=flag
        viewHomeworkByClass(flag)
    }
    function viewQuestion(row) {
      let CURRENT_HOMEWORK= JSON.stringify(row)
      localStorage.setItem('CURRENT_HOMEWORK',CURRENT_HOMEWORK)
      let getHomeworkProblemIdParams = {homeworkId: row.id}
      let problemId = 0
      let token = localStorage.getItem('token')
      API.getHomeworkProblemId(getHomeworkProblemIdParams,token).then(res3=>{
        if(res3.data.success==true){
            problemId = res3.data.content[0]
            viewProblemDetail(problemId)
        }
        else{
        console.log(res3.data)

        }
      }
      ).catch(e=>{
                  console.log(e)
                })
      
    }
    function viewProblemDetail(index) {
                let detail ={}
                detail.id = index
                let token = localStorage.getItem('token')
                API.questionDetail(detail,token).then(res=>{
                    localStorage.setItem("CURRENT_PROBLEM",JSON.stringify(res.data.content))

                    router.push({ path: "/trainQuestion" });
                    //这里必需写在请求体内因为函数会晚执行
                }).catch(e=>{
                    console.log(e)
                })
                    

            }


</script>

<style scoped>
.all {
  display: flex;
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-card ::v-deep .el-card__header {
  background-color: grey;
}
.col2-cell-style {
  color: #409eff;
  cursor: pointer;
}
.box-card {
  width: 70%;
  margin-left: 5%;
}

.box-card1 {
  width: 200px;
  height: 150px;
  margin-left: 5%;
}
.submitted{
  color: #16a085;
  cursor: pointer;
}
.over{
  color:orange;
  cursor: pointer;
}
</style>